<?php
#
# dmBridge: a data access framework for CONTENTdm(R)
#
# Copyright © 2009, 2010, 2011 Board of Regents of the Nevada System of Higher
# Education, on behalf of the University of Nevada, Las Vegas
#

/**
 * @author Alex Dolski <alex.dolski@unlv.edu>
 * @license http://www.opensource.org/licenses/mit-license.php
 */
abstract class DMXMLRepresentationTransformer
extends DMAbstractRepresentationTransformer {

	const XMLNS = "http://digital.library.unlv.edu";

	/** @var DOMDocument */
	protected $dxml;
	/** @var boolean */
	protected $pretty_print = false;


	public function __construct() {
		$this->dxml = new DOMDocument("1.0", "utf-8");
		$this->dxml->preserveWhiteSpace = false;
		$this->reset();
	}

	/**
	 * Resets the content of the DOMDocument.
	 */
	protected function reset() {
		$this->dxml->loadXML(
			'<dmBridgeResponse xmlns:xlink="http://www.w3.org/1999/xlink"/>');
	}

	/**
	 * @param bool
	 */
	public final function setPrettyPrint($bool) {
		$this->pretty_print = (bool) $bool;
	}

	protected function output() {
		$this->dxml->documentElement->appendChild(
			$this->dxml->createElement("copyright",
				DMConfigXML::getInstance()->getFeedCopyright()));
		$this->dxml->documentElement->appendChild(
			$this->dxml->createElement("querySeconds", $this->getQSeconds()));
		if ($this->pretty_print) $this->dxml->formatOutput = true;
		$this->dxml->documentElement->setAttribute("version", $this->getVersion());
		$return = $this->dxml->saveXML($this->dxml->documentElement);
		$this->reset();
		return $return;
	}

	/**
	 * Adds a built-in schema to the XML representation.
	 *
	 * @param string name
	 */
	protected function addSchema($name) {
		$uri = clone DMHTTPRequest::getCurrent()->getURI();
		$uri->unsetQuery();
		$uri->setParams("api/1/schema/xml/" . $name . ".xsd");
		$this->addSchemaAtURI($uri);
	}

	/**
	 * @param DMURI uri
	 */
	protected function addSchemaAtURI(DMURI $uri) {
		$this->dxml->documentElement->setAttribute(
			"xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
		$this->dxml->documentElement->setAttribute("xmlns", self::XMLNS);
		$this->dxml->documentElement->setAttribute("xsi:schemaLocation",
			sprintf("%s %s", self::XMLNS, $uri));
	}

	/**
	 * @return int
	 */
	public function getVersion() {
		return $this->version;
	}

}
